package com.lyshop.yinying.adapters;

import android.content.Context;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.lyshop.yinying.R;
import com.lyshop.yinying.activitys.LoginRegisterActivity;
import com.lyshop.yinying.application.MyApplication;
import com.lyshop.yinying.base.BaseActivity;
import com.lyshop.yinying.base.BaseRVAdapter;
import com.lyshop.yinying.bean.CalendarBean;
import com.lyshop.yinying.bean.DayBean;
import com.lyshop.yinying.bean.FollowOrderBean;
import com.lyshop.yinying.bean.FollowOrderRequestBean;
import com.lyshop.yinying.bean.GifBean;
import com.lyshop.yinying.bean.ImageItemBean;
import com.lyshop.yinying.bean.ImportantBean;
import com.lyshop.yinying.bean.NewsNoticeBean;
import com.lyshop.yinying.bean.SellOrderInfoBean;
import com.lyshop.yinying.bean.ShopGoodsListBean;
import com.lyshop.yinying.core.AppAction;
import com.lyshop.yinying.interfaces.OnItemClickListener;
import com.lyshop.yinying.utils.DataUtils;
import com.lyshop.yinying.utils.FastClickUtil;
import com.lyshop.yinying.utils.GlideUtils;
import com.lyshop.yinying.utils.LogUtil;
import com.lyshop.yinying.utils.RouteUtil;
import com.lyshop.yinying.utils.StringUtil;
import com.lyshop.yinying.utils.TimeCount;
import com.lyshop.yinying.utils.ToastUtil;
import com.lyshop.yinying.utils.Utils;
import com.lyshop.yinying.view.CreateOrderModule;
import com.lyshop.yinying.view.CustomTextView;
import com.lyshop.yinying.view.ImageCycleView;
import com.lyshop.yinying.view.LevelPopupWindow;
import com.lyshop.yinying.view.MarqueeTextView;
import com.lyshop.yinying.view.MyGridView;
import com.lyshop.yinying.view.ProGroupBeanPopupWindow;
import com.lyshop.yinying.view.TextViewSwitcher;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    private LayoutInflater layoutInflater;
    private AppAction mAppAction;
    private HomeListener mHomeListener;
    private List<NewsNoticeBean> mNewsNoticeBeanList = new ArrayList<>();//公告
    private List<ImageItemBean> mImageList = new ArrayList<>();//banner
    private List<GoodsAllBean> mGoodsList = new ArrayList<>();//热门商品
    private Map<String, GifBean> mGifMap = new HashMap<>();//广告位
    private ImportantBean impDataBean;//重要数据
    private List<SellOrderInfoBean> profitSquareList = new ArrayList<>();//牛单
    private boolean isShowTip;//是否显示安全提示
    private List<ShopGoodsListBean> mHomeGoodsList = new ArrayList<>();
    private List<FollowOrderBean> mFollowList = new ArrayList<>();
    private List<CalendarBean> mCalendarList = new ArrayList<>();
    private List<DayBean> mDayList = new ArrayList<>();

    private boolean isResetTimer = false;
    private int mChooseProfit = 0;//商城和跟单tabid 0商场 1跟单
    //    private FollowOrderRequestBean mFollowOrderRequestBean;
    private MyApplication myApplication;
    private BaseActivity mActivity;

    private final int HEADER_INDEX = 0;//顶部header
    private final int BANNER_INDEX = 1;//banner
    private final int MENU_INDEX = 2;//menu图标
    private final int PROBEAN_INDEX = 3;//热门商品
    private final int ADVERT_INDEX = 4;//广告位
    private final int IMPORTANT_INDEX = 5;//重要数据
    private final int PROFIT_SQUARE = 6;//牛单广场
    private final int TIP_INDEX = 7;//安全提示
    private final int FRONT_FIXED_ITEM_COUNT = 8;//商城和跟单中心
    private FollowOrderRequestBean mFollowOrderRequestBean;//跟单请求bean
    private HotProViewHolder hotProViewHolder;


    public HomeAdapter(Context context, HomeListener listener) {
        mContext = context;
        mActivity = (BaseActivity) context;
        layoutInflater = LayoutInflater.from(mContext);
        mHomeListener = listener;
        myApplication = ((MyApplication) mContext.getApplicationContext());
        mAppAction = ((MyApplication) mContext.getApplicationContext()).getAppAction();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case HEADER_INDEX:
                return new HeadViewHolder(layoutInflater.inflate(R.layout.item_type_home_head, parent, false));
            case BANNER_INDEX:
                return new BannerViewHolder(layoutInflater.inflate(R.layout.item_type_home_banner, parent, false));
            case MENU_INDEX:
                return new MenuViewHolder(layoutInflater.inflate(R.layout.item_type_home_menu, parent, false));
            case PROBEAN_INDEX:
                hotProViewHolder = new HotProViewHolder(layoutInflater.inflate(R.layout.item_type_home_hot_pro, parent, false));
                return hotProViewHolder;
            case ADVERT_INDEX:
                return new AdvertViewHolder(layoutInflater.inflate(R.layout.item_type_home_advert, parent, false));
            case IMPORTANT_INDEX:
                return new ImportantDataViewHolder(layoutInflater.inflate(R.layout.item_type_home_important_data, parent, false));
            case PROFIT_SQUARE:
                return new ProfitSquareViewHolder(layoutInflater.inflate(R.layout.item_type_home_square_list, parent, false));
            case TIP_INDEX:
                return new SafeTipViewHolder(layoutInflater.inflate(R.layout.item_type_home_safe_tip, parent, false));
            case FRONT_FIXED_ITEM_COUNT:
                return new MarketAndOrderViewHolder(layoutInflater.inflate(R.layout.item_type_home_market_order, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        long startTime = System.currentTimeMillis();
        if (holder instanceof HeadViewHolder) {
            ((HeadViewHolder) holder).setData();
        } else if (holder instanceof BannerViewHolder) {
            ((BannerViewHolder) holder).setData();
        } else if (holder instanceof MenuViewHolder) {
            ((MenuViewHolder) holder).setData();
        } else if (holder instanceof HotProViewHolder) {
            ((HotProViewHolder) holder).setData();
        } else if (holder instanceof AdvertViewHolder) {
            ((AdvertViewHolder) holder).setData();
        } else if (holder instanceof ImportantDataViewHolder) {
            ((ImportantDataViewHolder) holder).setData();
        } else if (holder instanceof ProfitSquareViewHolder) {
            ((ProfitSquareViewHolder) holder).setData();
        } else if (holder instanceof SafeTipViewHolder) {
            ((SafeTipViewHolder) holder).setData();
        } else if (holder instanceof MarketAndOrderViewHolder) {
            ((MarketAndOrderViewHolder) holder).setData();
        }

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        LogUtil.d("dangzt", "Item at position " + position + " took " + duration + " ms to load.");
    }

    @Override
    public int getItemViewType(int position) {
        if (position < FRONT_FIXED_ITEM_COUNT) {
            return position;
        } else {
            return FRONT_FIXED_ITEM_COUNT;
        }
    }

    @Override
    public int getItemCount() {
        return FRONT_FIXED_ITEM_COUNT + 1;
    }

    public void setNewsNoticeList(List<NewsNoticeBean> bean) {
        mNewsNoticeBeanList = bean;
        notifyItemChanged(HEADER_INDEX, true);
    }

    public void updateNewer() {
        notifyItemChanged(HEADER_INDEX, true);
    }

    public void setImageList(List<ImageItemBean> imageList) {
        mImageList = imageList;
        notifyItemChanged(BANNER_INDEX, true);
    }

    public void setDayList(List<DayBean> dayList) {
        mDayList = dayList;
        notifyItemChanged(FRONT_FIXED_ITEM_COUNT, true);
    }

    public void setGoodsList(List<GoodsAllBean> goodsList) {
        this.mGoodsList = goodsList;
        notifyItemChanged(PROBEAN_INDEX, true);
//        if (hotProViewHolder != null){
//            hotProViewHolder.setData();
//        }
    }

    public void setGifList(Map<String, GifBean> gifMap) {
        this.mGifMap = gifMap;
        notifyItemChanged(ADVERT_INDEX, true);
    }

    public void setImportantData(ImportantBean bean) {
        long endTime = 0;
        if (impDataBean != null) {
            endTime = impDataBean.end_time;
        }
        isResetTimer = impDataBean == null || Math.abs(bean.end_time - endTime) > 10;//初始化或修正时间误差
        impDataBean = bean;
        if (!isResetTimer) {
            impDataBean.end_time = endTime;//保留原时间
        }
        notifyItemChanged(IMPORTANT_INDEX, true);
    }

    public void setProfitSquareList(List<SellOrderInfoBean> list) {
        profitSquareList = list;
        notifyItemChanged(PROFIT_SQUARE, true);
    }

    public void setShowTip(boolean showTip) {
        isShowTip = showTip;
        notifyItemChanged(TIP_INDEX, true);
    }

    public void setHomeGoodsList(List<ShopGoodsListBean> list) {
        this.mHomeGoodsList = list;
        notifyBottomTypeList();
    }

    public void setFollowList(List<FollowOrderBean> followList) {
        this.mFollowList = followList;
        notifyBottomTypeList();
    }

//    public void setDayList(List<DayBean> dayList) {
//        mDayList = dayList;
//        notifyItemChanged(FRONT_FIXED_ITEM_COUNT, true);
//    }

    public void setEconomicsList(List<CalendarBean> dayList) {
        mCalendarList = dayList;
        notifyItemChanged(FRONT_FIXED_ITEM_COUNT, true);
    }

    public void notifyBottomTypeList() {
        notifyItemChanged(FRONT_FIXED_ITEM_COUNT, true);
    }

    public boolean isNoticeEmpty() {
        return mNewsNoticeBeanList.isEmpty();
    }

    public boolean isBannerEmpty() {
        return mImageList.isEmpty();
    }

    public boolean isHotEmpty() {
        return mGoodsList.isEmpty();
    }

    public boolean isGifEmpty() {
        return mGifMap.isEmpty();
    }

    public boolean isImportantEmpty() {
        return impDataBean == null;
    }

    public boolean isProfitSquareEmpty() {
        return profitSquareList.isEmpty();
    }

    public boolean isHomeGoodsEmpty() {
        return mHomeGoodsList.isEmpty();
    }

    public boolean isEconomicsEmpty() {
        return mCalendarList.isEmpty();
    }

    public boolean isFollowEmpty() {
        return mFollowList.isEmpty();
    }

    public boolean isDayListEmpty() {
        return mDayList.isEmpty();
    }

    public List<FollowOrderBean> getmFollowList() {
        return mFollowList;
    }

    private class HeadViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, ImageCycleView.ImageCycleViewListener {
        private LinearLayout ll_customer_service;
        private TextView tv_app_name;
        private View ll_message;
        private View view_message_dot;
        private RelativeLayout rl_notice;
        private TextViewSwitcher ts_notice;
        private ImageView iv_guide;


        HeadViewHolder(View itemView) {
            super(itemView);

            ll_customer_service = itemView.findViewById(R.id.ll_customer_service);
            ll_message = itemView.findViewById(R.id.ll_message);
            tv_app_name = itemView.findViewById(R.id.tv_app_name);
            view_message_dot = itemView.findViewById(R.id.view_message_dot);
            iv_guide = itemView.findViewById(R.id.iv_guide);
            rl_notice = itemView.findViewById(R.id.rl_notice);
            ts_notice = itemView.findViewById(R.id.ts_notice);

            ll_customer_service.setOnClickListener(this);
            ll_message.setOnClickListener(this);
            tv_app_name.setOnClickListener(this);
            iv_guide.setOnClickListener(this);
        }

        private void setData() {
            LogUtil.d("head setdata");
            boolean hasMessage = DataUtils.getBooleanSPByTag(mContext, DataUtils.SP_HAS_MESSAGE);
            if (hasMessage) {
                view_message_dot.setVisibility(View.VISIBLE);
            } else {
                view_message_dot.setVisibility(View.GONE);
            }

            if (!DataUtils.isLogin(mContext)) {
                iv_guide.setVisibility(View.VISIBLE);
            } else {
                iv_guide.setVisibility(View.GONE);
            }

            if (null != mNewsNoticeBeanList && mNewsNoticeBeanList.size() > 0) {
                rl_notice.setVisibility(View.VISIBLE);
                ts_notice.setAdapter(new RollingTextAdapter() {
                    @Override
                    public int getCount() {
                        return mNewsNoticeBeanList.size() > 0 ? mNewsNoticeBeanList.size() : 0;
                    }

                    @Override
                    public View getView(Context context, View contentView, int position) {
                        View view = View.inflate(context, R.layout.item_notice_scroll, null);
                        MarqueeTextView tv_report = view.findViewById(R.id.it_tv);
                        String desc = mNewsNoticeBeanList.get(position).title;
                        tv_report.setText(desc);
                        return view;
                    }
                });
                ts_notice.setOnItemClickListener(new TextViewSwitcher.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        RouteUtil.toWebViewActivity(mActivity, mNewsNoticeBeanList.get(position).url);
                    }
                });

                if (mNewsNoticeBeanList.size() > 1) {
                    ts_notice.startFlipping();
                }
            } else {
                rl_notice.setVisibility(View.GONE);
            }
        }

        @Override
        public void onClick(View v) {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            switch (v.getId()) {
                case R.id.ll_customer_service:
                    mHomeListener.onClickCustomService();
                    break;
                case R.id.ll_message:
                    mHomeListener.onClickMessage();
                    break;
                case R.id.tv_app_name:
                    if (!DataUtils.isLogin(mContext)) {
                        ((BaseActivity) mContext).onLogoutStatus();
                    }
                    break;
                case R.id.iv_guide:
                    RouteUtil.toRechargeActivity((BaseActivity) mContext);
                    break;
            }
        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {
            GlideUtils.showImageOptions(mContext, imageURL, imageView);
        }

        @Override
        public void onImageClick(ImageItemBean info, int postion, View imageView) {
            mHomeListener.onClickBanner(info.url);
        }
    }

    private class BannerViewHolder extends RecyclerView.ViewHolder implements ImageCycleView.ImageCycleViewListener {

        private ImageCycleView icv_image;

        public BannerViewHolder(View itemView) {
            super(itemView);
            icv_image = itemView.findViewById(R.id.icv_image);
        }

        private void setData() {
            LogUtil.d("banner setdata");
            if (mImageList.size() > 0) {
                icv_image.setImageResources(mImageList, this);
                icv_image.setVisibility(View.VISIBLE);
            } else {
                icv_image.setVisibility(View.GONE);
            }
        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {
            RequestOptions requestOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .transform(new RoundedCorners(8));
            Glide.with(mContext).load(imageURL).apply(requestOptions).into(imageView);
        }

        @Override
        public void onImageClick(ImageItemBean info, int position, View imageView) {
            mHomeListener.onClickBanner(info.url);
        }
    }

    private class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private View rl_ticket;
        private View rl_study;
        private View rl_follow;
        private View rl_customer;


        MenuViewHolder(View itemView) {
            super(itemView);
            rl_study = itemView.findViewById(R.id.rl_study);
            rl_customer = itemView.findViewById(R.id.rl_customer);
            rl_ticket = itemView.findViewById(R.id.rl_ticket);
            rl_follow = itemView.findViewById(R.id.rl_follow);


            rl_study.setOnClickListener(this);
            rl_customer.setOnClickListener(this);
            rl_ticket.setOnClickListener(this);
            rl_follow.setOnClickListener(this);
        }

        private void setData() {
            LogUtil.d("menu setdata");
        }

        @Override
        public void onClick(View v) {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            switch (v.getId()) {
                case R.id.rl_study:
                    mHomeListener.onClickInvestSchool();
                    break;
                case R.id.rl_ticket:
                    mHomeListener.onClickTicket();
                    break;
                case R.id.rl_customer:
                    mHomeListener.onClickCustomService();
                    break;
                case R.id.rl_follow:
                    mHomeListener.onClickFollowOrder();
                    break;

            }
        }
    }

    private class HotProViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private final RecyclerView rv_list;
//        private final ImageView iv_show_all;
        private HomeHotItemAdapter homeHotItemAdapter;

        HotProViewHolder(View itemView) {
            super(itemView);
            rv_list = itemView.findViewById(R.id.rv_list);
//            iv_show_all = itemView.findViewById(R.id.iv_show_all);
            LinearLayoutManager manager = new LinearLayoutManager(mContext) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            manager.setSmoothScrollbarEnabled(false);
            rv_list.setHasFixedSize(true);
            rv_list.setNestedScrollingEnabled(false);
            rv_list.setFocusable(false);
            rv_list.setLayoutManager(manager);
//            iv_show_all.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (homeHotItemAdapter != null) {
////                        homeHotItemAdapter.setOpenAll(true);
//                        iv_show_all.setVisibility(View.GONE);
//                    }
//                }
//            });
        }

        private void setData() {
            if (homeHotItemAdapter == null) {
                homeHotItemAdapter = new HomeHotItemAdapter();
                rv_list.setAdapter(homeHotItemAdapter);
            }
            homeHotItemAdapter.setDataList(mGoodsList);
            homeHotItemAdapter.setOnItemClickListener(new OnItemClickListener<GoodsAllBean>() {
                @Override
                public void onItemClick(List<GoodsAllBean> data, View view, int position, long id) {
                    if (null != mGoodsList && mGoodsList.size() > 0) {
                        if (position != mGoodsList.size()) {
                            GoodsAllBean mGroupBean = mGoodsList.get(position);
                            mHomeListener.onClickHotPro(mGroupBean);
                        }
                    } else {
                        ToastUtil.showToast(mContext, "加载商品失败，请重启应用");
                    }
                }
            });
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
//                case R.id.iv_home_open:
//                    isOpen = !isOpen;
//                    if (isOpen) {
//                        iv_home_open.setImageResource(R.mipmap.icon_home_arrow_close);
//                    } else {
//                        iv_home_open.setImageResource(R.mipmap.icon_home_arrow_open);
//                    }
//                    adapter.setOpenAll(isOpen);
//                    break;
            }
        }
    }

    private class AdvertViewHolder extends RecyclerView.ViewHolder {

        private final ImageView iv_gif;

        public AdvertViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_gif = itemView.findViewById(R.id.iv_gif);
            iv_gif.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouteUtil.routePageByUrl(mActivity, mGifMap.get("1").link);
                }
            });
        }

        private void setData() {
            GifBean bean = mGifMap.get("1");
            if (bean == null || TextUtils.isEmpty(bean.img)) {
                iv_gif.setVisibility(View.GONE);
            } else {
                iv_gif.setVisibility(View.VISIBLE);
                GlideUtils.showImageFitxyOptions(mContext, bean.img, iv_gif);
            }
        }
    }

    private class ImportantDataViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TimeCount timeCount;
        private View rl_border;
        private TextView tv_title;
        private TextView tv_time;
        private TextView tv_value;
        private TextView tv_result;
        private TextView tv_time_count;
        private ImageView iv_time_icon;

        ImportantDataViewHolder(View itemView) {
            super(itemView);
            rl_border = itemView.findViewById(R.id.rl_border);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
            tv_value = (TextView) itemView.findViewById(R.id.tv_value);
            tv_result = (TextView) itemView.findViewById(R.id.tv_result);
            tv_time_count = (TextView) itemView.findViewById(R.id.tv_time_count);
            iv_time_icon = (ImageView) itemView.findViewById(R.id.iv_time_icon);

            rl_border.setOnClickListener(this);
        }

        private void setData() {
            if (impDataBean != null && impDataBean.show_type == 1) {
                rl_border.setVisibility(View.VISIBLE);

                tv_title.setText(impDataBean.title);
                tv_time.setText(String.format("公布时间　%s", Utils.getWeek(impDataBean.end_time_unix * 1000)));
                tv_value.setText(String.format("前值：%s　| 预测：%s |　实际：%s", impDataBean.front_val, impDataBean.forecast_val, impDataBean.actual_val));
                if (StringUtil.isEmpty(impDataBean.push_text)){
                    tv_result.setVisibility(View.GONE);
                }else {
                    tv_result.setVisibility(View.VISIBLE);
                    if (impDataBean.push_text.contains("利空")){
                        tv_result.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_5ab76b));
                    }else {
                        tv_result.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_ea484d));
                    }
                    tv_result.setText(impDataBean.push_text);
                }
                if (impDataBean.end_time > 0) {
                    if (isResetTimer) {
                        startTimer();
                        isResetTimer = false;
                    }
                } else {
                    if (timeCount != null) {
                        timeCount.finishTimeCount();
                    } else {
                        setResult();
                    }
                }
            } else {
                rl_border.setVisibility(View.GONE);
            }
        }

        private void startTimer() {
            if (timeCount != null) {
                timeCount.finishTimeCount();
            }
            final long TIME_STAMP = impDataBean.end_time * 1000;
            timeCount = new TimeCount(TIME_STAMP, 1000) {
                final int HASH_CODE = this.hashCode();

                @Override
                public void onTick(long millisUntilFinished) {
                    if (timeCount != null && HASH_CODE == timeCount.hashCode()) {
                        impDataBean.end_time = (millisUntilFinished / 1000);
                        long hourStamp = millisUntilFinished / 1000 / 60 / 60;
                        long minStamp = ((millisUntilFinished / 1000) % (60 * 60)) / 60;
                        long secondStamp = (millisUntilFinished / 1000) % 60;
                        tv_time_count.setText((hourStamp >= 10 ? hourStamp : "0" + hourStamp) + ":" + (minStamp >= 10 ? minStamp : "0" + minStamp) + ":"
                                + (secondStamp >= 10 ? secondStamp : "0" + secondStamp));
                    }
                }

                @Override
                public void onFinish() {
                    if (timeCount != null && HASH_CODE == timeCount.hashCode()) {
                        if (impDataBean.end_time <= 1) {
                            impDataBean.end_time = 0;
                            setResult();
                        }
                    }
                }
            };
            timeCount.start();
            tv_time_count.setVisibility(View.VISIBLE);
            iv_time_icon.setVisibility(View.VISIBLE);
        }

        private void setResult() {
            iv_time_icon.setVisibility(View.GONE);
            switch (impDataBean.goods_status) {
                case 1:
                    setColor(R.color.buy_red, "影响较大");
                    break;
                case 2:
                    setColor(R.color.buy_green, "影响较小");
                    break;
                case 3:
                    setColor(R.color.text_main, "待公布");
                    break;
                default:
                    tv_time_count.setVisibility(View.GONE);
                    break;
            }
        }

        private void setColor(int color, String content) {
            tv_time_count.setVisibility(View.VISIBLE);
            tv_time_count.setText(content);
        }

        @Override
        public void onClick(View view) {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            switch (view.getId()) {
                case R.id.rl_border:
                    mHomeListener.onClickImportantData(impDataBean.link, impDataBean.title);
                    break;
            }
        }
    }

    private class ProfitSquareViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private LinearLayout ll_profit;
        private TextViewSwitcher ts_notice;


        public ProfitSquareViewHolder(View itemView) {
            super(itemView);
            ll_profit = itemView.findViewById(R.id.ll_profit);
            ts_notice = itemView.findViewById(R.id.ts_notice);

            ll_profit.setOnClickListener(this);
        }

        public void setData() {
            if (null != profitSquareList && profitSquareList.size() > 0) {
                ll_profit.setVisibility(View.VISIBLE);

                ts_notice.setAdapter(new RollingTextAdapter() {
                    @Override
                    public int getCount() {
                        return profitSquareList.size() > 0 ? profitSquareList.size() : 0;
                    }

                    @Override
                    public View getView(Context context, View contentView, int position) {
                        View view = View.inflate(context, R.layout.item_home_notice_scroll, null);
                        TextView tv_describe = view.findViewById(R.id.tv_describe);
                        CustomTextView tv_rate_number = view.findViewById(R.id.tv_rate_number);
                        CustomTextView tv_win_money = view.findViewById(R.id.tv_win_money);

                        SellOrderInfoBean bean = profitSquareList.get(position);
                        String describe = bean.nick_name;
                        if (bean.pro_name != null && bean.pro_name.length() > 1) {
                            describe += "「" + bean.pro_name.substring(0, 1) + "商品」 用时" + FormatUtil.dateToStamp(bean.build_time_unix, bean.liqui_time_unix);
                        }
                        double orderMoney = ArithUtil.mul(bean.unit_price, bean.amount);
                        double present = 0;
                        if (orderMoney != 0) {
                            present = ArithUtil.mul(ArithUtil.div(Double.valueOf(bean.pro_loss), orderMoney), 100);
                        }
                        tv_rate_number.setText(ArithUtil.format(present) + "%");
                        tv_win_money.setText(ArithUtil.format(Double.valueOf(bean.pro_loss)) + "元");
                        tv_describe.setText(describe);
                        return view;
                    }
                });

                if (profitSquareList.size() > 1) {
                    ts_notice.startFlipping();
                }
            } else {
                ll_profit.setVisibility(View.GONE);
            }

        }

        @Override
        public void onClick(View v) {
            if (FastClickUtil.isFastClick()) {
                return;
            }
            switch (v.getId()) {
                case R.id.ll_profit:
                    mHomeListener.onClickProfitSquare();
                    break;
            }
        }
    }

    private class SafeTipViewHolder extends RecyclerView.ViewHolder {

        private final ImageView iv_tip;

        public SafeTipViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_tip = itemView.findViewById(R.id.iv_tip);
        }

        public void setData() {
            if (isShowTip) {
                iv_tip.setVisibility(View.VISIBLE);
            } else {
                iv_tip.setVisibility(View.GONE);
            }
        }
    }

    private class MarketAndOrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, LevelPopupWindow.LevelPopupListener, ProGroupBeanPopupWindow.ProGroupListener {

        private final RadioGroup rg_group;
        private final TextView tv_all;
        private final TextView tv_time;
        private final LinearLayout ll_choose_level;
        private final LinearLayout ll_choose_product;
        private final TextView tv_level_name;
        private final RelativeLayout rl_choose;
        private final TextView tv_choose_product;
        private final TextView tv_follow_check_more;
        private final RecyclerView rv_list;
        private final MyGridView gv_day;
        private HomeGoodsAdapter homeGoodsAdapter;
        private FollowOrderAdapter followOrderAdapter;
        private LevelPopupWindow chooseLevelWindow;
        private ProGroupBeanPopupWindow chooseWindow;
        private EconomicsAdapter mEconomicsAdapter;
        private LinearLayout ll_no_data;

        public MarketAndOrderViewHolder(@NonNull View itemView) {
            super(itemView);
            rg_group = itemView.findViewById(R.id.rg_group);
            tv_all = itemView.findViewById(R.id.tv_all);
            tv_time = itemView.findViewById(R.id.tv_time);
            ll_choose_level = itemView.findViewById(R.id.ll_choose_level);
            ll_choose_product = itemView.findViewById(R.id.ll_choose_product);
            tv_level_name = itemView.findViewById(R.id.tv_level_name);
            rl_choose = itemView.findViewById(R.id.rl_choose);
            tv_choose_product = itemView.findViewById(R.id.tv_choose_product);
            tv_follow_check_more = itemView.findViewById(R.id.tv_follow_check_more);
            ll_no_data = itemView.findViewById(R.id.ll_no_data);
            gv_day = itemView.findViewById(R.id.gv_day);

            rv_list = itemView.findViewById(R.id.rv_list);
            LinearLayoutManager manager = new LinearLayoutManager(mContext) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            manager.setSmoothScrollbarEnabled(false);
            rv_list.setLayoutManager(manager);
            rv_list.setHasFixedSize(true);
            rv_list.setNestedScrollingEnabled(false);
            rv_list.setFocusable(false);

            rg_group.setOnCheckedChangeListener(this);
            tv_all.setOnClickListener(this);
            tv_time.setOnClickListener(this);
            ll_choose_level.setOnClickListener(this);
            ll_choose_product.setOnClickListener(this);
            tv_follow_check_more.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_all:
                    changeStatus(0);

                    if (null != chooseLevelWindow) {
                        chooseLevelWindow.resetChoose();
                    }
                    if (null != chooseWindow) {
                        chooseWindow.resetChoose();
                    }

                    mFollowOrderRequestBean.openTime = false;
                    mFollowOrderRequestBean.follow = false;
                    mFollowOrderRequestBean.level = "";
                    mFollowOrderRequestBean.contract = "";
                    mHomeListener.onChangeFollowRequestBean(mFollowOrderRequestBean);
                    break;
                case R.id.tv_time:
                    changeStatus(1);

                    mFollowOrderRequestBean.openTime = true;
                    mHomeListener.onChangeFollowRequestBean(mFollowOrderRequestBean);
                    break;
                case R.id.ll_choose_level:
                    if (null == chooseLevelWindow) {
                        chooseLevelWindow = new LevelPopupWindow(mActivity, this);
                    }
                    int[] location1 = new int[2];
                    rl_choose.getLocationOnScreen(location1);
                    chooseLevelWindow.showAsDropDown(rl_choose);
                    break;
                case R.id.ll_choose_product:
                    if (null == chooseWindow) {
                        chooseWindow = new ProGroupBeanPopupWindow(mActivity, this);
                    }
                    int[] location = new int[2];
                    rl_choose.getLocationOnScreen(location);
                    chooseWindow.showAsDropDown(rl_choose);
                    break;
                case R.id.tv_follow_check_more:
                    RouteUtil.toFollowOrderCenterActivity((BaseActivity) mContext);
                    break;
            }
        }

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_goods_mail:
                    mChooseProfit = 0;
                    break;
                case R.id.rb_follow_order:
                    mChooseProfit = 1;
                    break;
                case R.id.rb_calendar:
                    mChooseProfit = 2;
                    break;
            }
            setTextStyle(mChooseProfit);
            mHomeListener.onClickListType(mChooseProfit);
        }

        private void setTextStyle(int index) {
            for (int i = 0; i < rg_group.getChildCount(); i++) {
                RadioButton childAt = (RadioButton) rg_group.getChildAt(i);
                if (index == i) {
                    childAt.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                } else {
                    childAt.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                }
            }
        }

        public void setData() {
            if (mChooseProfit == 0) {
                rl_choose.setVisibility(View.GONE);
                gv_day.setVisibility(View.GONE);

                if (mHomeGoodsList.isEmpty()) {
                    ll_no_data.setVisibility(View.VISIBLE);
                    rv_list.setVisibility(View.GONE);
                    return;
                } else {
                    ll_no_data.setVisibility(View.GONE);
                    rv_list.setVisibility(View.VISIBLE);
                }

                if (homeGoodsAdapter == null) {
                    homeGoodsAdapter = new HomeGoodsAdapter();
                    homeGoodsAdapter.setOnItemClickListener(new OnItemClickListener<ShopGoodsListBean>() {
                        @Override
                        public void onItemClick(List<ShopGoodsListBean> data, View view, int position, long id) {
                            mHomeListener.onClickBuyGoods(data.get(position));
                        }
                    });
                }

                GridLayoutManager manager = new GridLayoutManager(mContext, 2) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                };
                rv_list.setLayoutManager(manager);
                homeGoodsAdapter.setShopGoodsListBeans(mHomeGoodsList);
                rv_list.setAdapter(homeGoodsAdapter);
            } else {
                if (mChooseProfit == 1) {
                    rl_choose.setVisibility(View.VISIBLE);
                    gv_day.setVisibility(View.GONE);

                    if (mFollowList.isEmpty()) {
                        ll_no_data.setVisibility(View.VISIBLE);
                        rv_list.setVisibility(View.GONE);
                        return;
                    } else {
                        ll_no_data.setVisibility(View.GONE);
                        rv_list.setVisibility(View.VISIBLE);
                    }
                } else {
                    rl_choose.setVisibility(View.GONE);
                    gv_day.setVisibility(View.VISIBLE);

                    if (mCalendarList.isEmpty()) {
                        ll_no_data.setVisibility(View.VISIBLE);
                        rv_list.setVisibility(View.GONE);
                        return;
                    } else {
                        ll_no_data.setVisibility(View.GONE);
                        rv_list.setVisibility(View.VISIBLE);
                    }
                }

                LinearLayoutManager manager = new LinearLayoutManager(mContext) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                };
                rv_list.setLayoutManager(manager);
            }

            if (mChooseProfit == 1) {
                if (followOrderAdapter == null) {
                    followOrderAdapter = new FollowOrderAdapter();
                    followOrderAdapter.setFollowOrderListener(new FollowOrderAdapter.FollowOrderListener() {
                        @Override
                        public void onClickDetail(String userId) {
                            RouteUtil.toFollowOrderUserActivity(mActivity, userId);
                        }

                        @Override
                        public void onClickFollow(int position) {
                            if (mFollowList == null || mFollowList.isEmpty()) return;
                            if (!DataUtils.getUserId(mActivity).equals("0") && DataUtils.isLogin(mActivity)) {
                                //更新用户信息
                                myApplication.updateUserDetail();
                                FollowOrderBean bean = mFollowList.get(position);
                                GoodsAllBean mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                                mHomeListener.onClickFollowGroupBean(mGroupBean);
                                if (null != mGroupBean) {
                                    CreateOrderModule.getInstance().createOrder(mActivity, bean.trade_type, bean.order_id, mGroupBean, bean.unit_price, bean.user_id, 0);
                                } else {
                                    ToastUtil.showToast(mActivity, "未获取的产品信息");
                                }
                            } else {
                                RouteUtil.toLoginRegisterActivity(mActivity, LoginRegisterActivity.TYPE_LOGIN);
                            }
                        }

                        @Override
                        public void onClickGoKLine(int position) {
                            if (mFollowList == null || mFollowList.isEmpty()) return;

                            FollowOrderBean bean = mFollowList.get(position);
                            GoodsAllBean mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                            RouteUtil.toMarketActivity(mActivity, mGroupBean.pro_code);
                        }
                    });
                }
                followOrderAdapter.setDataList(mFollowList);
                rv_list.setAdapter(followOrderAdapter);
            } else if (mChooseProfit == 2) {
                if (null == gv_day.getAdapter()) {
                    final HomeDayAdapter dayAdapter = new HomeDayAdapter(mContext, mDayList);
                    gv_day.setAdapter(dayAdapter);
                    gv_day.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            dayAdapter.setPosition(position);
                            mHomeListener.onClickDay(mDayList.get(position));
                        }
                    });
                }

                mEconomicsAdapter = new EconomicsAdapter(mContext, mCalendarList);
                mEconomicsAdapter.setOnItemClickListener(new BaseRVAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(List data, View view, int position, long id) {
                        mHomeListener.onClickCalendar(mCalendarList.get(position));
                    }
                });
                rv_list.setAdapter(mEconomicsAdapter);
            }
        }

        private void changeStatus(int status) {
            if (status == 1) {
                tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
                tv_time.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            } else if (status == 2) {
                tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
                tv_level_name.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            } else if (status == 3) {
                tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
                tv_choose_product.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            } else {
                tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
                tv_time.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
                tv_level_name.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
                tv_choose_product.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));

                tv_choose_product.setText("品种");
                tv_level_name.setText("等级");
            }
        }

        @Override
        public void onClickLevel(String name, int level) {
            tv_level_name.setText(name);

            changeStatus(2);

            mFollowOrderRequestBean.level = String.valueOf(level);
            mHomeListener.onChangeFollowRequestBean(mFollowOrderRequestBean);
        }

        @Override
        public void onClickProduct(String name, String code) {
            tv_choose_product.setText(name);

            changeStatus(3);

            mFollowOrderRequestBean.contract = code;
            mHomeListener.onChangeFollowRequestBean(mFollowOrderRequestBean);
        }
    }

    public void setFollowRequestBean(FollowOrderRequestBean bean) {
        this.mFollowOrderRequestBean = bean;
    }

    public interface HomeListener {
        /**
         * 点击Banner
         *
         * @param url
         */
        void onClickBanner(String url);

        /**
         * 点击热门产品
         */
        void onClickHotPro(GoodsAllBean bean);

        /**
         * 点击福利专区
         */
        void onClickWelfare();

        /**
         * 点击新手秘籍
         */
        void onClickInvestSchool();

        /**
         * 点击增益榜单
         */
        void onClickProfit();

        /**
         * 点击活动专区
         */
        void onClickHotActivity();

        /**
         * 点击商城
         */
        void onClickShopMall();

        /**
         * 点击跟单
         */
        void onClickFollowOrder();

        /**
         * 点击牛单广场
         */
        void onClickProfitSquare();

        /**
         * 点击客服
         */
        void onClickCustomService();

        /**
         * 点击交易策略
         */
//        void onClickNewsItem(NewsItemBean bean);

        /**
         * 点击重要数据刷新
         */
        void onClickRefresh();

        /**
         * 点击重要数据详情
         */
        void onClickImportantData(String url, String title);

        /**
         * 点击底部type切换
         *
         * @param type
         */
        void onClickListType(int type);

        void onClickRecharge();

        void onClickNotice();

        /**
         * 新手送券
         */
        void onClickTicket();

        void onClickNewTeacher();

//        void onClickGifAdvert(HomeData data);

        void onClickSign();

        void onChangeFollowRequestBean(FollowOrderRequestBean bean);

//        void onClickFollowGroupBean(ProGroupBean bean);

//        void onClickDay(DayBean bean);

//        void onClickCalendar(CalendarBean bean);

        /**
         * 消息列表
         */
        void onClickMessage();

        void onClickTask();

        void onClickLuckyDay();

        void onClickBuyGoods(ShopGoodsListBean bean);

        /**
         * 跟单弹窗回调，刷新最新价格
         *
         * @param bean
         */
        void onClickFollowGroupBean(GoodsAllBean bean);

        /**
         * 点击财经日历
         *
         * @param bean
         */
        void onClickCalendar(CalendarBean bean);

        /**
         * 点击日期
         *
         * @param bean
         */
        void onClickDay(DayBean bean);
    }
}
